package qimao.com.edu.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import qimao.com.edu.entity.Users;
import qimao.com.edu.service.UsersService;
import qimao.com.edu.service.impl.UsersServiceImpl;

@WebServlet("/admin/updateUser.do")
public class UpdateUserServlet extends HttpServlet {
    
    private UsersService usersService = new UsersServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        
        response.setContentType("application/json;charset=UTF-8");
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        
    
        // 1. 获取正确的请求参数
        Integer userId = Integer.parseInt(request.getParameter("userId"));
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
        String userStatus =request.getParameter("state");
        if (userId == null) {
            result.put("message", "用户ID不能为空");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return;
        }
        
        // 2. 创建用户对象并设置值
        Users user = new Users();
        user.setUserId(userId);
        user.setUsername(userName);
        user.setPassword(password);
        user.setStatus(("active".equals(userStatus) ? 1 : 0));
        System.out.println("==="+user);
        
        int rowsAffected = usersService.updateUser(user);
        
        if (rowsAffected > 0) {
            result.put("success", true);
            result.put("message", "用户信息更新成功");
        } else {
            result.put("message", "用户不存在或更新失败");
        }
        
        response.getWriter().write(objectMapper.writeValueAsString(result));
    }
}